package com.cjh.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author cjh
 * @date 2021/3/29 11:38
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/instances")
    public List<ServiceInstance> instances() {

        return discoveryClient.getInstances("provider");
    }

    /**
     * 不使用ribbon
     * @return
     */
//    @GetMapping("/index")
//    public String index() {
//        List<ServiceInstance> provider = discoveryClient.getInstances("provider");
//        int index = ThreadLocalRandom.current().nextInt(provider.size());
//        String url = provider.get(index).getUri() + "/provider/index";
//        return "consumer随机远程调用provier：" + this.restTemplate.getForObject(url, String.class);
//    }

    /**
     * 使用ribbon
     * @return
     */
    @GetMapping("/index")
    public String index() {
        return "consumer随机远程调用provier：" + this.restTemplate.getForObject("http://provider/provider/index", String.class);
    }

}
